package android_serialport_api.sample;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.Environment;
import com.clouddot.baipai.ui.activity.BaseActivity;
import com.ys.usbreader.UsbReader;

import java.security.InvalidParameterException;

/**
 * Created by huangrusheng on 2017/11/25.
 */

public abstract class UsbReaderActivity extends BaseActivity {

    protected application mApplication;
    protected UsbReader mUsbReader;
    protected String mInputData;
    private ReadThread mReadThread;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (application) getApplication();
        try {
            mUsbReader = mApplication.getUsbReader();
            mReadThread = new ReadThread();
            mReadThread.start();

        } catch (SecurityException e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

            DisplayError(R.string.error_security);
        } catch (InvalidParameterException e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

            DisplayError(R.string.error_configuration);
        } catch (Throwable e) {
            Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

            DisplayError(R.string.error_configuration);
        }
    }

    @Override
    protected void onDestroy() {
        if (mReadThread != null)
            mReadThread.interrupt();
        mApplication.closeUsbReader();
        mReadThread = null;
        super.onDestroy();
    }

    protected abstract void onDataReceived(final String inputData);


    private class ReadThread extends Thread {

        @Override
        public void run() {
            super.run();
            while(!isInterrupted()) {
                try {
                    mInputData = mUsbReader.getInputData();
                    if (mInputData == null || mInputData == "") return;
                    Env.info("刷卡卡号："+mInputData);
                    onDataReceived(mInputData);

                } catch (Exception e) {
                    Env.error(Environment.getInstance().fileUtil.Errorinfo(e));

                    return;
                }
            }
        }
    }



    private void DisplayError(int resourceId) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Error");
        b.setMessage(resourceId);
        b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                UsbReaderActivity.this.finish();
            }
        });
        b.show();
    }

}
